package czk.concrent.threadpool.newFixedThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/6/30 22:08
 */
public class NewFixedThreadPoolDemo {
    public static void main(String[] args) throws InterruptedException {
        // 创建固定大小的线程数
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        // 线程一执行
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName()+"  执行的1");
        });
        // 线程二执行
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName()+"  执行的2");
        });
        // 进入阻塞队列，由线程一或者线程二执行
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName()+"  执行的3");
        });
        Thread.sleep(2*1000);
        executorService.shutdown();
        // 指定线程名称的线程池的创建
        // 创建时指定线程工厂，匿名内部类实现
        ExecutorService executorService1= Executors.newFixedThreadPool(2, new ThreadFactory() {
            // 原子变量
            private AtomicInteger index=new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"myThread"+index.getAndIncrement());
            }
        });
        // 线程一执行
        executorService1.execute(()->{
            System.out.println(Thread.currentThread().getName()+"  执行的1");
        });
        // 线程二执行
        executorService1.execute(()->{
            System.out.println(Thread.currentThread().getName()+"  执行的2");
        });
        // 进入阻塞队列，由线程一或者线程二执行
        executorService1.execute(()->{
            System.out.println(Thread.currentThread().getName()+"  执行的3");
        });
        executorService1.shutdown();
    }
}
